package com.example.lotterysystem.common.interceptor;

import com.example.lotterysystem.common.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final String USER_TOKEN = "user_token";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头
        String token = request.getHeader(USER_TOKEN);
        // 打印获取信息
        log.info("获取 token: {}", USER_TOKEN);
        log.info("获取路径: {}", request.getRequestURI());
        // 解析令牌
        Claims claims = JWTUtils.parseToken(token);
        if (null == claims) {
            log.error("JWT 令牌解析失败!");
            response.setStatus(401);
            return false;
        }
        log.info("解析 JWT 令牌成功！");
        return true;
    }
}
